package shark.tenant.service.impl;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import shark.tenant.service.TenantSchemaService;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class TenantSchemaServiceImpl implements TenantSchemaService, ApplicationContextAware {

    private List<String> tables = new ArrayList<>();

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    private String driver;

    @Value("${spring.datasource.url}")
    private String url;

    @Override
    public List<String> getTenantSchemaList() {
        return tables;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        try {
            this.tables = sqlSessionQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private List<String> sqlSessionQuery() throws SQLException {
        List<String> tenantTables = getSelect();
        return tenantTables;
    }

    public List<String> getSelect() throws SQLException {
        String sql = "select table_name from sys_tenant_table";
        Connection conn = getCon();
        PreparedStatement pst = null;
        List<String> list = new ArrayList<String>();
        try {
            pst = (PreparedStatement) conn.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                list.add(rs.getString("table_name"));
            }
        } catch (Exception e) {
        } finally {
            conn.close();
        }
        return list;
    }

    private Connection getCon() {
        Connection conn=null;
        try{
            Class.forName(driver);
            conn=(Connection) DriverManager.getConnection(url,username,password);
        }catch(Exception e){
            e.printStackTrace();
        }
        return conn;
    }
}
